package com.chuhe.starry.service.impl;

import com.chuhe.common.domain.dto.MessageSendDto;
import com.chuhe.common.domain.entity.ChatSessionUser;
import com.chuhe.common.domain.entity.UserContact;
import com.chuhe.common.domain.enums.MessageTypeEnum;
import com.chuhe.common.domain.enums.UserContactTypeEnum;
import com.chuhe.common.utils.StringTools;
import com.chuhe.starry.dao.ChatSessionUserDao;
import com.chuhe.starry.dao.UserContactDao;
import com.chuhe.starry.service.ChatSessionService;
import com.chuhe.starry.service.ChatSessionUserService;
import com.chuhe.starry.websocket.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: 楚河
 * @Date: 2025年05月21日17:19
 */
@Service
public class ChatSessionUserServiceImpl implements ChatSessionUserService {
    @Autowired
    private ChatSessionUserDao chatSessionUserDao;
    @Lazy
    @Autowired
    private MessageHandler messageHandler;
    @Lazy
    @Autowired
    private UserContactDao userContactDao;

    /**
     * 修改昵称后发送消息
     * @Author: 楚河
     * @Date: 2025-05-23 17:06
     */
    @Override
    public void updateRedundanceInfo(String contactName, String contactId) {
        if(StringTools.isEmpty(contactName)){
            return;
        }
        ChatSessionUser updateInfo = new ChatSessionUser();
        updateInfo.setContactName(contactName);
        chatSessionUserDao.updateContactName(updateInfo,contactId);

        UserContactTypeEnum contactTypeEnum = UserContactTypeEnum.getByPrefix(contactId);
        if(contactTypeEnum == UserContactTypeEnum.GROUP){
            //群
            MessageSendDto messageSendDto = new MessageSendDto();
            messageSendDto.setContactType(UserContactTypeEnum.getByPrefix(contactId).getType());
            messageSendDto.setContactId(contactId);
            messageSendDto.setExtendData(contactName);
            messageSendDto.setMessageType(MessageTypeEnum.CONTACT_NAME_UPDATE.getType());
            messageHandler.sendMessage(messageSendDto);
        }else {
            //个人 给每个联系人发送更改昵称的消息
            List<UserContact> userContactList = userContactDao.selectUserContactList(contactId);
            for (UserContact userContact : userContactList) {
                MessageSendDto messageSendDto = new MessageSendDto();
                messageSendDto.setContactType(contactTypeEnum.getType());
                messageSendDto.setContactId(userContact.getUserId());
                messageSendDto.setExtendData(contactName);
                messageSendDto.setMessageType(MessageTypeEnum.CONTACT_NAME_UPDATE.getType());
                messageSendDto.setSendUserId(contactId);
                messageSendDto.setSendUserNickName(contactName);
                messageHandler.sendMessage(messageSendDto);
            }
        }
    }
}
